<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\SystemConfig as SystemConfigModel;
use think\facade\Db;

class SystemConfig extends BaseService
{
    protected $model;
    public function __construct()
    {
        Parent::__construct();
        $this->model = new SystemConfigModel();
    }

    use ServiceResponse;

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-10-10 14:09:48
     * @param [type] @required
     * @return Renderable
     */
    public function getList(array $where, $field = '*', int $page = 1, int $limit = 100)
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }
        $where['is_del'] = 0;

        $total = $this->model->where($where)->count();
        $list = $this->model
            ->where($where)
            ->field($field)
            ->page($page, $limit)
            ->select()
            ->toArray();

        $creatorArr =  array_filter(array_unique(array_column($list, 'creator')), function ($value) {
            return $value !== null;
        });
        $creatorList = Db::name('operator')->whereIn('id', $creatorArr)->column('id,cname', 'id');


        foreach ($list as $key => &$value) {
            $value['creator'] = $creatorList[$value['creator']]['cname'] ?? '';
        }

        $data = ['list' => $list, 'total' => $total];
        return $this->success($data);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-10-11 14:26:39
     * @param [type] @required
     * @return Renderable
     */
    public function save($data)
    {
        try {
            $res = $this->model->create($data);
            if ($res) {
                $this->logger->logOperation($res->id, 'SystemConfig', '添加', '添加系统配置');
                return $this->success();
            } else {
                return $this->error(500001);
            }
        } catch (\Throwable $th) {
            return $this->error(500001, '服务器内部错误：' . $th->getMessage());
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-10-11 14:27:53
     * @param [type] @required
     * @return Renderable
     */
    public function update($where, $data)
    {
        $where['is_del'] = 0;
        $res = $this->model->where($where)->find();
        if (!$res) {
            return $this->error(500001);
        }
        try {
            $res = $this->model->where($where)->update($data);
            if ($res >= 0) {
                $this->logger->logOperation($where['id'], 'SystemConfig', '更新', '更新系统配置');
                return $this->success();
            } else {
                return $this->error(500001);
            }
        } catch (\Throwable $th) {
            return $this->error(500001, '服务器内部错误：' . $th->getMessage());
        }
    }
}
